package com.ld.curator.tools;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @author:ld
 * @create:2020-04-30 15:11
 * @description: Master选举
 */
public class CuratorMaster {

    private static String master_path = "/curator_master_path";

    private static CuratorFramework client = CuratorFrameworkFactory
            .builder()
            .connectString("127.0.0.1:2181")
            .retryPolicy(new ExponentialBackoffRetry(1000,3))
            .build();

    public static void main(String[] args) throws InterruptedException {
        //开启客户端连接
        client.start();

        //创建Leader选举对象
        LeaderSelector selector = new LeaderSelector(client, master_path, new LeaderSelectorListenerAdapter() {
            @Override
            public void takeLeadership(CuratorFramework curatorFramework) throws Exception {
                System.out.println("成为Master角色");
                System.out.println("------>线程名：" + Thread.currentThread().getName());
            }
        });
        //自动排队
        selector.autoRequeue();
        //开启Leader选举器
        selector.start();
        System.out.println("线程名：" + Thread.currentThread().getName());
        Thread.sleep(Integer.MAX_VALUE);
    }


}
